/*
*  TCLStereoDepthAlg.cpp
*	Modified: Chao Xiang
*  Date: 2019-5-9
*
*/

#include "OpenCVconfig.h"
#include "opencv2/core.hpp"

#include <stdio.h>
#include <time.h>
#include <iostream>

#include "potrace/potracelib.h"
#include "potrace/bitmap.h"
#include "potrace/backend_pgm.h"


using namespace cv;
using namespace std;


void SmoothEdge(cv::Mat & mask_out, const cv::Mat & mask_in, float scale) {
	potrace_param_t * param = potrace_param_default();
	if (!param) {
		printf("Error allocating parameters: %s\n", strerror(errno));
		exit(-1);
	}
	param->turdsize = 0;

	potrace_bitmap_t * bm;
	potrace_state_t * st;

	// convert from matrix into bitmap
	bm = bitmapFromMat(mask_in, 0);
	// core process: trace the edges
	st = potrace_trace(param, bm);
	if (!st || st->status != POTRACE_STATUS_OK) {
		printf("Error tracing bitmap: %s\n", strerror(errno));
		exit(-1);
	}

	// use trace result to draw anti-alias binary mask
	// using PGM backend
	imginfo_t imginfo;
	imginfo.pixwidth = bm->w;
	imginfo.pixheight = bm->h;
	
	calc_dimensions(&imginfo, st->plist, scale);

	render_pgm(mask_out, st->plist, &imginfo);

	bm_free(bm);
	potrace_state_free(st);
	potrace_param_free(param);
}


int main(int argc, char** argv) {
	cv::Mat im_ = cv::imread("F:/dump/masks/mask_0.png");
	cv::Mat im_grey, mask;
	cv::cvtColor(im_, im_grey, CV_BGR2GRAY);
	cv::imshow("origin", im_grey);
	cv::waitKey(0);

	double start, stop, freq = cv::getTickFrequency();
	start = cv::getTickCount();
	SmoothEdge(mask, im_grey, 2.0);
	stop = cv::getTickCount();
	std::cout << "time cost: " << 1000 * (stop - start) / freq << std::endl;
	cv::imshow("mask_smooth", mask);
	cv::waitKey(0);

	cv::imwrite("F:/dump/masks/mask_0_smooth.png", mask);

	system("pause");
	return 0;
}
